package com.example.demo.controller.usercontroller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.demo.common.ErrorCode;
import com.example.demo.common.Result;
import com.example.demo.context.UserContext;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.FileUploadUtil;
import com.example.demo.utils.MD5Utils;
import com.example.demo.vo.UserLoginVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2025-01-27 20:52:33
 */
@RestController
@RequestMapping("user/user")
@Tag(name = "客户端用户接口")
@RequiredArgsConstructor
public class UserController{
    private final UserService userService;
    @Value("${server.url:http://localhost:8080}")
    private String serverUrl;
    @PostMapping("/login")
    @Operation(description = "用户登录")
    public Result<UserLoginVo>loginVoResult(@RequestParam("username")String username, @RequestParam("password")String password){
       return  Result.success(userService.login(username,password));
    }

    /**
     *
     */
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件到 avatar 子目录
            String fileUrl = serverUrl + FileUploadUtil.uploadFile(file, "avatar/");

            // 更新用户头像
            User user = new User();
            user.setId(UserContext.getUserId());
            user.setAvatar(fileUrl);
            userService.updateById(user);

            return Result.success(fileUrl);
        } catch (IOException e) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    @PostMapping("/uploadImg")
    public Result<String> uploadImg(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件到 avatar 子目录
            String fileUrl = serverUrl + FileUploadUtil.uploadFile(file, "avatar/");
            return Result.success(fileUrl);
        } catch (IOException e) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
    }


    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        // 1. 参数校验
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return Result.error(ErrorCode.ACCOUNT_EMPTY);
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return Result.error(ErrorCode.PASSWORD_EMPTY);
        }
        if (user.getPhone() == null || !user.getPhone().matches("^1[3-9]\\d{9}$")) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }

        // 2. 检查用户名是否已存在
        if (userService.checkUsernameExists(user.getUsername())) {
            return Result.error(ErrorCode.USERNAME_EXIST);
        }

        // 4. 设置用户默认属性
        user.setPassword(MD5Utils.encrypt(user.getPassword()));
        user.setStatus(1); // 设置状态为正常
        user.setCreateTime(LocalDateTime.now()); // 设置创建时间

        // 5. 保存用户信息
        try {
            userService.save(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public Result<Void> updateUserInfo(@RequestBody User user) {
        user.setId(UserContext.getUserId());
        // 只允许更新昵称
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setAvatar(user.getAvatar());
        updateUser.setNickname(user.getNickname());
        userService.updateById(updateUser);
        return Result.success();
    }
    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        User user = userService.getById(UserContext.getUserId());
        return Result.success(user);
    }
}

